#include <iostream>

// 定长内存池
template <typename T>
class ObjectPool
{

public:
    T *alloc()
    {
        T *obj;
        size_t objSize = sizeof(T) < sizeof(void *) ? sizeof(void *) : sizeof(T);

        if (_freeList)
        {
            void *next = *(void **)_freeList;
            obj = (T *)_freeList;
            _freeList = next;
        }
        else
        {

            if (_remainSize < objSize)
            {
                _memory = (char *)malloc(128 * 1024);
                _remainSize = 128 * 1024;
                if (!_memory)
                {
                    throw std::bad_alloc();
                }
            }
            obj = (T *)_memory;
            _remainSize -= objSize;
            _memory += objSize;
        }

        new (obj) T;
        return obj;
    }

    void dealloc(T *obj)
    {
        obj->~T();
        *(void **)obj = _freeList;
        _freeList = obj;
    }

private:
    void *_freeList = nullptr;
    size_t _remainSize = 0;
    char *_memory = nullptr;
};